//
//  GiftDetailCollectionViewController.m
//  GiftNote
//
//  Created by wsh on 15/8/17.
//  Copyright (c) 2015年 GN. All rights reserved.
//

#import "GiftDetailCollectionViewController.h"
#import "GiftDetailCollectionViewCell.h"
#import "PKRequestManager.h"
#import "MJRefresh.h"
#import "Screen.h"
#import "HomeMenueView.h"
#import "HomeDetailBuyViewController.h"

//  用判断刷新的方式(是下拉刷新还是上拉加载)
typedef NS_ENUM(NSInteger, RefreashType){
    RefreashTypeNew,  //  下拉刷新
    RefreashTypeMore     //  上拉加载
};



@interface GiftDetailCollectionViewController () <HomeMenuDelegate>
@property (nonatomic, strong) NSMutableArray *dataArray;

@property (nonatomic, assign) NSInteger num;  // 每次加载的数据个数
@property (nonatomic, assign) RefreashType refreashType; //  刷新的方式

@property (nonatomic, strong) HomeMenueView *menu;


@property (nonatomic, assign) NSInteger index;  //  选择的排序下表序号

@property (nonatomic, strong) NSString *currentUrl;   //  当前的解析网址
@end

@implementation GiftDetailCollectionViewController

static NSString * const reuseIdentifier = @"Cell";


- (NSMutableArray *)dataArray{

    if (_dataArray == nil) {
        self.dataArray = [NSMutableArray arrayWithArray:0];
    }
    return _dataArray;
}


- (void)viewWillDisappear:(BOOL)animated{
    
    [self.menu menuDismiss];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.collectionView.backgroundColor = [UIColor colorWithRed:240/256.0 green:250/256.0 blue:250/256.0 alpha:1];
    
    self.clearsSelectionOnViewWillAppear = NO;
    //  设置标题
    self.navigationItem.title = _nameString;
    
    //  改变标题的颜色
    NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:
                                [UIColor whiteColor],
                                NSForegroundColorAttributeName, nil];
    [self.navigationController.navigationBar setTitleTextAttributes:attributes];
    
    //  改变返回按钮的颜色
    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
    
    //  设置一开始加载的数据个数以及调用刷新函数
    _num = 0;
    [self refreashData];
    _index = 0;
    //  刷新界面
    [self readData];
    
    //  注册cell
    [self.collectionView registerClass:[GiftDetailCollectionViewCell class] forCellWithReuseIdentifier:reuseIdentifier];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-paixu"] style:UIBarButtonItemStylePlain target:self action:@selector(sortAction)];
    
    NSArray *array = @[@"默认排序", @"按热度排序", @"价格从低到高", @"价格从高到低"];
    _menu = [[HomeMenueView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH - 160, 64, 150, 176) array:array];
    _menu.delegate = self;
    _menu.layer.masksToBounds = YES;

    _menu.layer.cornerRadius = 25;
    

}





#pragma mark --- 解析数据
- (void)readData{

    switch (_index) {
        case 0:
            _currentUrl = [_urlString stringByAppendingString:[NSString stringWithFormat:@"%ld",(long)_num]];
            break;
        case 1:
            _currentUrl = [_urlString stringByAppendingString:[NSString stringWithFormat:@"%ld&sort=hot",(long)_num]];
            break;
        case 2:
            _currentUrl = [[_urlString stringByAppendingString:[NSString stringWithFormat:@"%ld",(long)_num]] stringByAppendingString:[NSString stringWithFormat:@"&sort=price%%3Aasc"]];
            break;
        case 3:
            _currentUrl = [_urlString stringByAppendingString:[NSString stringWithFormat:@"%ld&sort=price%%3Adesc",(long)_num]];
            break;
        default:
            break;
    }
    
    //  注意:当字符串中出现%字符时,用%%代替原来一个%
    
    [PKRequestManager manager:GET requestWith:_currentUrl parDic:nil finish:^(NSData *data) {
        
        if (_refreashType == RefreashTypeNew) {
            [self.dataArray removeAllObjects];
        }
        NSDictionary *parDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves  error:nil];
        NSArray *arr = parDic[@"data"][@"items"];
        for (NSDictionary *dic in arr) {
            GiftDetailModel *model = [[GiftDetailModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.dataArray addObject:model];
        }
        
        [self.collectionView reloadData];
    } error:^(NSError *error) {
        
    }];
}




#pragma mark --- UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
  
    return 1;
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {

    return _dataArray.count;
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    GiftDetailCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
    GiftDetailModel *model = _dataArray[indexPath.item];
    
    cell.layer.masksToBounds = YES;
    cell.layer.cornerRadius = 5;
    cell.model = model;
    cell.backgroundColor = [UIColor whiteColor];
    return cell;
}



#pragma mark --- UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    return CGSizeMake((SCREEN_WIDTH - 20) / 2.0, (SCREEN_WIDTH - 20) / 2.0 + 80);

}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    
    return UIEdgeInsetsMake(0, 5, 0, 5);
}



#pragma mark --- UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    HomeDetailBuyViewController *homeVC = [[HomeDetailBuyViewController alloc] init];
    GiftDetailModel *model = _dataArray[indexPath.item];
    
    homeVC.ID = [model.ID stringValue];
    
    UITabBarController *tabBVC = (UITabBarController *)self.view.window.rootViewController;
    UINavigationController *navi = tabBVC.viewControllers[2];
    [navi pushViewController:homeVC animated:YES];
    
}



#pragma mark --- action
- (void)refreashData{
    
    [self.collectionView addGifHeaderWithRefreshingTarget:self refreshingAction:@selector(refeashNew)];
    [self.collectionView addGifFooterWithRefreshingTarget:self refreshingAction:@selector(refreashMore)];
}

//  刷新数据(重新开始加载)
- (void)refeashNew{
    
    _num = 0;
    _refreashType = RefreashTypeNew;
    [self readData];
    [self.collectionView.gifHeader endRefreshing];
}

//  加载数据(加载一次,增加20条数据)
- (void)refreashMore{
    
    _num += 20;
    _refreashType = RefreashTypeMore;
    [self readData];
    
    
    [self.collectionView.gifFooter endRefreshing];
}


- (void)sortAction{
    
    if (_menu.isShow) {
        [self.menu menuDismiss];
    } else {
        [self.menu menuShow:self.navigationController];
//        self.menu.dim
    }
}


//  HomeMenueView的代理方法,即根据不同的排序下表,来调用不同的数据源
- (void)transportMenuName:(NSString *)name index:(NSInteger)index{

    _index = index;
    [self readData];
    [self.collectionView.gifHeader beginRefreshing];

}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark <UICollectionViewDelegate>

/*
// Uncomment this method to specify if the specified item should be highlighted during tracking
- (BOOL)collectionView:(UICollectionView *)collectionView shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath {
	return YES;
}
*/

/*
// Uncomment this method to specify if the specified item should be selected
- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}
*/

/*
// Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item
- (BOOL)collectionView:(UICollectionView *)collectionView shouldShowMenuForItemAtIndexPath:(NSIndexPath *)indexPath {
	return NO;
}

- (BOOL)collectionView:(UICollectionView *)collectionView canPerformAction:(SEL)action forItemAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
	return NO;
}

- (void)collectionView:(UICollectionView *)collectionView performAction:(SEL)action forItemAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
	
}
*/

@end
